package com.mico.micochange.trade;

import com.alibaba.fastjson.JSONObject;
import com.mico.micochange.common.ExchangeCacheUtils;
import com.mico.micochange.server.MicoThread;
import com.mico.xchange.Exchange;
import com.mico.xchange.ExchangeFactory;
import com.mico.xchange.binance.BinanceExchange;
import com.mico.xchange.binance.service.BinanceQueryOrderParams;
import com.mico.xchange.binance.service.BinanceTradeHistoryParams;
import com.mico.xchange.binance.service.BinanceTradeService;
import com.mico.xchange.bitstamp.BitstampExchange;
import com.mico.xchange.bitstamp.dto.trade.BitstampOrderStatusResponse;
import com.mico.xchange.bitstamp.service.BitstampTradeServiceRaw;
import com.mico.xchange.chaoex.Chaoex;
import com.mico.xchange.chaoex.ChaoexExchange;
import com.mico.xchange.chaoex.ChaoexUtils;
import com.mico.xchange.chaoex.dto.trade.ChaoexLogin;
import com.mico.xchange.chaoex.dto.trade.ChaoexOrder;
import com.mico.xchange.chaoex.dto.trade.results.ChaoexOpenOrdersResult;
import com.mico.xchange.chaoex.service.ChaoexTradeServiceRaw;
import com.mico.xchange.currency.CurrencyPair;
import com.mico.xchange.dto.Order;
import com.mico.xchange.dto.marketdata.Trade;
import com.mico.xchange.dto.trade.UserTrade;
import com.mico.xchange.dto.trade.UserTrades;
import com.mico.xchange.fcoin.FCoinExchange;
import com.mico.xchange.fcoin.dto.trade.FCoinOpenOrder;
import com.mico.xchange.fcoin.service.FCoinTradeServiceRaw;
import com.mico.xchange.huobi.HuobiExchange;
import com.mico.xchange.huobi.service.HuobiTradeService;
import com.mico.xchange.okcoin.OkCoinExchange;
import com.mico.xchange.okcoin.dto.trade.OkCoinOrder;
import com.mico.xchange.okcoin.dto.trade.OkCoinOrderResult;
import com.mico.xchange.okcoin.service.OkCoinTradeServiceRaw;
import org.apache.mina.core.session.IoSession;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by chenst on 2018/5/6.
 */
public class GetOrderThread extends MicoThread{
    public GetOrderThread(IoSession session, String message) {
        super(session, message);
    }


    @Override
    public Map doHuobiChange(JSONObject json)  throws Exception{
        //初始化数据
        String orderId = json.get("orderId").toString();

        Exchange exchange = ExchangeCacheUtils.getExchange(HuobiExchange.class.getName(),  json.get("apiKey").toString(), json.get("secretKey").toString());
        HuobiTradeService tradeService = (HuobiTradeService)exchange.getTradeService();
        Map<String,Object> retMap = new HashMap<String,Object>();
        String[] ids = orderId.split("@");

        List<Order> retList = new ArrayList<Order>();
        for(String id : ids){
            if(id==null || "".equals(id))
                continue;

            Collection<Order> lst = tradeService.getOrder(id);
            retList.add(lst.iterator().next());
        }

        retMap.put("result",retList);
        return retMap;
    }

    @Override
    public Map doBinanceChange(JSONObject json)  throws Exception{
        //初始化数据
        String orderId = json.get("orderId").toString();

        Exchange exchange = ExchangeCacheUtils.getExchange(BinanceExchange.class.getName(),  json.get("apiKey").toString(), json.get("secretKey").toString());
        BinanceTradeService tradeService = (BinanceTradeService)exchange.getTradeService();
        Map<String,Object> retMap = new HashMap<String,Object>();
        String baseSymbol = "";
        String counterSymbol = "";
        try {
            baseSymbol = json.get("baseSymbol").toString();
            counterSymbol = json.get("counterSymbol").toString();
        }catch (Exception e){
            throw new Exception("no currencyPair info");
        }
        CurrencyPair currencyPair = new CurrencyPair(baseSymbol,counterSymbol);

        String[] ids = orderId.split("@");
        Collection<Order> lst = null;
        for(String id : ids) {
            if(id==null || "".equals(id))
                continue;

            BinanceQueryOrderParams orderQueryParamCurrencyPair = new BinanceQueryOrderParams(currencyPair, id);
            if(lst!=null) {
                lst = tradeService.getOrder(orderQueryParamCurrencyPair);
            }else{
                lst.addAll(tradeService.getOrder(orderQueryParamCurrencyPair));
            }
        }


        //查询返回成交价格
        BinanceTradeHistoryParams binanceTradeHistoryParams = new BinanceTradeHistoryParams(currencyPair);
        UserTrades trades =  tradeService.getTradeHistory(binanceTradeHistoryParams);
        BigDecimal finalPrice = new BigDecimal(0);
        BigDecimal fee = new BigDecimal(0);
        List<Order> retList = new ArrayList<Order>();
        for(Order order : lst){
            for(Trade trade : trades.getTrades()){
                UserTrade userTrade = (UserTrade)trade;
                if(userTrade.getOrderId().equals(order.getId())){
                    finalPrice = trade.getPrice().multiply(trade.getOriginalAmount());
                    fee = ((UserTrade) trade).getFeeAmount();


                    order.setFinalDealPrice(finalPrice);
                    order.setFee(fee);
                    retList.add(order);
                    break;
                }
            }
        }

        retMap.put("result",retList);
        return retMap;
    }

    @Override
    public Map doChaoexChange(JSONObject json) throws Exception {
        //初始化数据
        String orderId = json.get("orderId").toString();

        String baseSymbol = json.get("baseSymbol").toString();
        String counterSymbol = json.get("counterSymbol").toString();
        String sdate = json.get("startDate").toString();
        String edate = json.get("endDate").toString();
        String[] ids = orderId.split("@");
//        for(String id : ids) {
//            System.out.println("$$$$$$$$$"+id);
//        }

        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(ChaoexExchange.class.getName(), json.get("apiKey").toString(), json.get("secretKey").toString());
        ChaoexLogin chaoexLogin = ChaoexUtils.getToken(json.get("apiKey").toString(),json.get("secretKey").toString(),json.get("loginPwd").toString());
        ChaoexTradeServiceRaw chaoexTradeServiceRaw = (ChaoexTradeServiceRaw)exchange.getTradeService();

        ChaoexOpenOrdersResult result = chaoexTradeServiceRaw.orderStatus(sdate,edate,ChaoexUtils.getCurrency(baseSymbol),ChaoexUtils.getCurrency(counterSymbol),chaoexLogin.getUid(),chaoexLogin.getToken());


        //防止token超时
        if("9999".equals(result.getStatus())) {
            chaoexLogin = ChaoexUtils.getNewToken(json.get("apiKey").toString(), json.get("secretKey").toString(), json.get("loginPwd").toString());
            result = chaoexTradeServiceRaw.orderStatus(sdate,edate,ChaoexUtils.getCurrency(baseSymbol), ChaoexUtils.getCurrency(counterSymbol), chaoexLogin.getUid(), chaoexLogin.getToken());
        }else if(!result.isSuccess()){
            throw new Exception(result.getError());
        }
        List<ChaoexOrder>  list =  result.getResult().getChaoexOpenOrderList();
        List<ChaoexOrder>  retList = new ArrayList<ChaoexOrder>();
        Map<String,Object> retMap = new HashMap<String,Object>();
        for(String id : ids) {
            if(id==null || "".equals(id))
                continue;
            for (ChaoexOrder order : list) {
                if (id.equals(order.getId())) {
                    retList.add(order);
                    break;
                }
            }
        }
        retMap.put("result",retList);
        return retMap;
    }

    public Map doBitstampChange(JSONObject json) throws Exception{
        //初始化数据
        String orderId = json.get("orderId").toString();

        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(BitstampExchange.class.getName(), json.get("apiKey").toString(), json.get("secretKey").toString());
        BitstampTradeServiceRaw tradeService = (BitstampTradeServiceRaw) exchange.getTradeService();
        BitstampOrderStatusResponse orderStatusResponse = tradeService.getBitstampOrder(Long.parseLong(orderId));

        Map<String,Object> retMap = new HashMap<String,Object>();
        retMap.put("result", orderStatusResponse);
        return null;
    }

    @Override
    public Map doOkexChange(JSONObject json) throws Exception {
        //初始化数据
        String orderId = json.get("orderId").toString();
        String baseSymbol = json.get("counterSymbol").toString();
        String counterSymbol = json.get("baseSymbol").toString();
        String symbol = counterSymbol.toLowerCase()+"_"+baseSymbol.toLowerCase();

        //现货交易
        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(OkCoinExchange.class.getName(),json.get("apiKey").toString(), json.get("secretKey").toString());
        OkCoinTradeServiceRaw okCoinTradeServiceRaw = (OkCoinTradeServiceRaw)exchange.getTradeService();
        OkCoinOrderResult result = okCoinTradeServiceRaw.getOrderHistory(symbol,"0","1","200");
        Map<String,Object> retMap = new HashMap<String,Object>();
        List<OkCoinOrder>  retList = new ArrayList<OkCoinOrder>();
        if(result.isResult()){
            String[] ids = orderId.split("@");
            for(String id : ids) {
                for (OkCoinOrder order : result.getOrders()) {
                    if (id.equals(order.getOrderId()+"")){
                        retList.add(order);
                        break;
                    }
                }
            }
        }
        retMap.put("result",retList);
        return retMap;
    }

    @Override
    public Map doFCoinExchange(JSONObject json) throws Exception {
        //初始化数据
        String orderId = json.get("orderId").toString();
        String baseSymbol = json.get("counterSymbol").toString();
        String counterSymbol = json.get("baseSymbol").toString();
        String symbol = counterSymbol.toLowerCase()+baseSymbol.toLowerCase();

        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(FCoinExchange.class.getName(),json.get("apiKey").toString(), json.get("secretKey").toString());
        FCoinTradeServiceRaw tradeService = (FCoinTradeServiceRaw)exchange.getTradeService();
        String[] ids = orderId.split("@");
        List<FCoinOpenOrder>  retList = new ArrayList<FCoinOpenOrder>();
        for(String id : ids) {
            FCoinOpenOrder order = tradeService.getOrder(id);
            if(order!=null){
                retList.add(order);
            }
        }
        Map<String,Object> retMap = new HashMap<String,Object>();
        retMap.put("result",retList);
        return retMap;
    }
}
